<template>
  <div class="create-event-page">
    <div class="page-header">
      <n-button quaternary @click="$router.back()">
        <n-icon :size="20">
          <ArrowBack />
        </n-icon>
      </n-button>
      <h1>创建事件</h1>
      <div></div>
    </div>
    
    <div class="page-content">
      <n-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-placement="top"
        @submit.prevent="handleSubmit"
      >
        <n-form-item path="event_type_id" label="事件类型">
          <!-- 移动端且从 popover 选择时显示为只读标签 -->
          <div v-if="isMobile && isFromPopover && selectedEventType" class="event-type-display">
            <div class="event-type-tag" :style="{ backgroundColor: selectedEventType.color }">
              <n-icon :size="18" style="color: white;">
                <component :is="getEventTypeIcon(selectedEventType.icon)" />
              </n-icon>
              <span class="event-type-name">{{ selectedEventType.name }}</span>
            </div>
            <n-button text type="primary" size="small" @click="changeEventType">
              更改
            </n-button>
          </div>
          <!-- 其他情况显示选择器 -->
          <n-select
            v-else
            v-model:value="form.event_type_id"
            placeholder="选择事件类型"
            :options="eventTypeOptions"
            @update:value="handleEventTypeChange"
          />
        </n-form-item>
        
        <n-form-item path="title" label="事件标题">
          <n-input
            v-model:value="form.title"
            placeholder="请输入事件标题"
          />
        </n-form-item>
        
        <n-form-item v-if="!isDietTrackingForm" path="description" label="事件描述">
          <n-input
            v-model:value="form.description"
            type="textarea"
            placeholder="请输入事件描述（可选）"
            :rows="3"
          />
        </n-form-item>
        
        <!-- 日期选择 -->
        <n-form-item path="start_date" label="日期">
          <n-date-picker
            v-model:value="startDateValue"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
            @update:value="handleStartDateChange"
          />
        </n-form-item>

        <!-- 时间范围选择 -->
        <n-form-item :label="timeLabel">
          <div class="time-range-container">
            <div class="time-input-group">
              <n-time-picker
                v-model:value="startTimeValue"
                placeholder="开始时间"
                format="HH:mm"
                style="width: 100%"
                @update:value="handleStartTimeChange"
              />
              <span v-if="!isDietTrackingForm" class="time-separator">→</span>
              <n-time-picker v-if="!isDietTrackingForm"
                v-model:value="endTimeValue"
                placeholder="结束时间"
                format="HH:mm"
                style="width: 100%"
                @update:value="handleEndTimeChange"
              />
            </div>
            <div v-if="timeRangeDisplay" class="time-display">
              {{ timeRangeDisplay }}
            </div>
          </div>
        </n-form-item>

        <!-- 结束日期（仅在跨天时显示） -->
        <n-form-item v-if="showEndDate" path="end_date" label="结束日期">
          <n-date-picker
            v-model:value="endDateValue"
            type="date"
            placeholder="选择结束日期"
            style="width: 100%"
            @update:value="handleEndDateChange"
          />
        </n-form-item>
        
        <n-form-item v-if="!isDietTrackingForm" path="priority" label="优先级">
          <n-select
            v-model:value="form.priority"
            placeholder="选择优先级"
            :options="priorityOptions"
          />
        </n-form-item>

        <!-- 重复设置 -->
        <n-form-item v-if="!isDietTrackingForm" label="重复设置">
          <n-space vertical>
            <n-checkbox v-model:checked="enableRecurrence">
              启用重复
            </n-checkbox>

            <div v-if="enableRecurrence" class="recurrence-settings">
              <n-grid :cols="3" :x-gap="12">
                <n-grid-item>
                  <n-form-item label="重复频率">
                    <n-select
                      v-model:value="recurrenceFrequency"
                      placeholder="选择频率"
                      :options="frequencyOptions"
                    />
                  </n-form-item>
                </n-grid-item>

                <n-grid-item>
                  <n-form-item label="间隔">
                    <n-input-number
                      v-model:value="recurrenceInterval"
                      :min="1"
                      :max="100"
                      placeholder="间隔"
                      style="width: 100%"
                    />
                  </n-form-item>
                </n-grid-item>

                <n-grid-item>
                  <n-form-item label="重复次数">
                    <n-input-number
                      v-model:value="recurrenceCount"
                      :min="1"
                      :max="365"
                      placeholder="次数"
                      style="width: 100%"
                    />
                  </n-form-item>
                </n-grid-item>
              </n-grid>
            </div>
          </n-space>
        </n-form-item>

        <!-- 动态表单字段 -->
        <div v-if="selectedEventType && selectedEventType.form_config">
          <div
            v-for="field in selectedEventType.form_config.fields"
            :key="field.name"
            class="dynamic-field"
            v-show="!shouldHideField(field)"
          >
            <n-form-item :label="field.label">
              <!-- 文本输入 -->
              <n-input
                v-if="field.type === 'text'"
                v-model:value="form.extra_data![field.name]"
                :placeholder="`请输入${field.label}`"
              />
              
              <!-- 多行文本 -->
              <n-input
                v-else-if="field.type === 'textarea'"
                v-model:value="form.extra_data![field.name]"
                type="textarea"
                :placeholder="`请输入${field.label}`"
                :rows="3"
              />
              
              <!-- 数字输入 -->
              <n-input-number
                v-else-if="field.type === 'number'"
                v-model:value="form.extra_data![field.name]"
                :placeholder="`请输入${field.label}`"
                style="width: 100%"
              />
              
              <!-- 选择器 -->
              <n-select
                v-else-if="field.type === 'select'"
                v-model:value="form.extra_data![field.name]"
                :placeholder="`请选择${field.label}`"
                :options="getFieldOptions(field)"
                @update:value="handleFieldChange(field, $event)"
              />

              <!-- 食物选择器 -->
              <FoodSelector
                v-else-if="field.type === 'food_selector'"
                v-model="form.extra_data![field.name]"
                :placeholder="`请选择${field.label}`"
              />

              <!-- 饮食跟踪表单 -->
              <DietTrackingForm
                v-else-if="field.type === 'food_intake_selector'"
                :model-value="form.extra_data?.[field.name] || { foods_intake: [] }"
                @update:model-value="(value) => handleDietTrackingUpdate(field.name, value)"
              />
            </n-form-item>
          </div>
        </div>
        
        <n-form-item>
          <n-space>
            <n-button type="primary" attr-type="submit" :loading="loading">
              创建事件
            </n-button>
            <n-button @click="$router.back()">
              取消
            </n-button>
          </n-space>
        </n-form-item>
      </n-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ArrowBack,
  Restaurant,
  Analytics,
  Create,
  Fitness,
  Book,
  Calendar as CalendarIconType,
  Heart,
  Briefcase
} from '@vicons/ionicons5'
import type { FormInst, FormRules } from 'naive-ui'
import { useEventsStore } from '@/stores/events'
import { formatDate } from '@/utils/date'
import type { CreateEventForm, EventType, FormField } from '@/types'
import FoodSelector from '@/components/foods/FoodSelector.vue'
import DietTrackingForm from '@/components/DietTrackingForm.vue'
import { useDevice } from '@/composables/useDevice'

const router = useRouter()
const route = useRoute()
const eventsStore = useEventsStore()
const { isMobile } = useDevice()

// 时间标签
const timeLabel = ref('时间');

// 是否为饮食跟踪表单
const isDietTrackingForm = ref(false);

// 是否从 popover 选择的事件类型
const isFromPopover = ref(false)

// 表单引用
const formRef = ref<FormInst | null>(null)

// 加载状态
const loading = ref(false)

// 图标映射
const iconMap: Record<string, any> = {
  restaurant: Restaurant,
  analytics: Analytics,
  create: Create,
  fitness: Fitness,
  book: Book,
  calendar: CalendarIconType,
  heart: Heart,
  briefcase: Briefcase
}

// 获取事件类型图标
const getEventTypeIcon = (iconName: string) => {
  return iconMap[iconName] || Create
}

// 更改事件类型
const changeEventType = () => {
  isFromPopover.value = false
  form.event_type_id = null as any
  selectedEventType.value = null
}

// 日期时间值
const startDateValue = ref<number | null>(null)
const startTimeValue = ref<number | null>(null)
const endDateValue = ref<number | null>(null)
const endTimeValue = ref<number | null>(null)

// 重复设置
const enableRecurrence = ref(false)
const recurrenceFrequency = ref<'daily' | 'weekly' | 'monthly'>('daily')
const recurrenceInterval = ref(1)
const recurrenceCount = ref<number | null>(null)
const recurrenceEndDateValue = ref<number | null>(null)

// 表单数据
const form = reactive<CreateEventForm>({
  event_type_id: null as any, // 默认为空，让用户主动选择
  title: '',
  description: '',
  start_date: '',
  end_date: '',
  start_time: '',
  end_time: '',
  duration_type: 'single',
  duration_value: 1,
  priority: 'medium',
  extra_data: {}
})

// 选中的事件类型
const selectedEventType = ref<EventType | null>(null)

// 事件类型选项
const eventTypeOptions = computed(() => {
  return eventsStore.eventTypes.map((type: any) => ({
    label: type.name,
    value: type.id
  }))
})

// 时间范围显示
const timeRangeDisplay = computed(() => {
  if (startTimeValue.value && endTimeValue.value) {
    const startTime = formatTime(new Date(startTimeValue.value))
    const endTime = formatTime(new Date(endTimeValue.value))
    return `${startTime} → ${endTime}`
  }
  return ''
})

// 是否显示结束日期
const showEndDate = ref(false)

// 格式化时间显示
const formatTime = (date: Date) => {
  return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 优先级选项
const priorityOptions = [
  { label: '低', value: 'low' },
  { label: '中', value: 'medium' },
  { label: '高', value: 'high' }
]

// 重复频率选项
const frequencyOptions = [
  { label: '每天', value: 'daily' },
  { label: '每周', value: 'weekly' },
  { label: '每月', value: 'monthly' }
]

// 表单验证规则
const rules: FormRules = {
  event_type_id: [
    { required: true, type: 'number', message: '请选择事件类型', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入事件标题', trigger: 'blur' }
  ],
  start_date: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ]
}

// 处理事件类型变化
const handleEventTypeChange = (value: number) => {
  selectedEventType.value = eventsStore.getEventType(value) || null
  // 重置额外数据
  form.extra_data = {}
  isDietTrackingForm.value = false;
  timeLabel.value = '时间';

  // 为food_selector和food_intake_selector字段初始化空数组
  if (selectedEventType.value?.form_config?.fields) {
    selectedEventType.value.form_config.fields.forEach(field => {
      if (field.type === 'food_selector') {
        form.extra_data![field.name] = []
      } else if (field.type === 'food_intake_selector') {
        isDietTrackingForm.value = true;
        timeLabel.value = '就餐时间';
        form.extra_data![field.name] = {
          meal_type: '',
          foods_intake: [],
          notes: ''
        }
      }
    })
  }
}

// 处理开始日期变化
const handleStartDateChange = (value: number | null) => {
  if (value) {
    form.start_date = formatDate(new Date(value), 'YYYY-MM-DD')
  } else {
    form.start_date = ''
  }
}

// 处理开始时间变化
const handleStartTimeChange = (value: number | null) => {
  if (value) {
    const date = new Date(value)
    form.start_time = `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:00`
  } else {
    form.start_time = ''
  }
}

// 处理结束日期变化
const handleEndDateChange = (value: number | null) => {
  if (value) {
    form.end_date = formatDate(new Date(value), 'YYYY-MM-DD')
  } else {
    form.end_date = ''
  }
}

// 处理结束时间变化
const handleEndTimeChange = (value: number | null) => {
  if (value) {
    const date = new Date(value)
    form.end_time = `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:00`
  } else {
    form.end_time = ''
  }
}



// 判断是否应该隐藏字段
const shouldHideField = (field: FormField) => {
  // 隐藏饮食规划中的餐次和计划卡路里字段
  if (selectedEventType.value?.name === '饮食规划') {
    return field.name === 'meal_type' || field.name === 'calories_planned'
  }
  return false
}

// 获取字段选项
const getFieldOptions = (field: FormField) => {
  if (field.name === 'diet_type') {
    // 饮食类型选择器
    return eventsStore.dietTypes.map(type => ({
      label: type.name,
      value: type.id
    }))
  }

  if (field.options) {
    return field.options.map(option => ({
      label: option,
      value: option
    }))
  }
  return []
}

// 处理字段变化
const handleFieldChange = (field: FormField, value: any) => {
  if (field.name === 'diet_type' && value) {
    // 当选择饮食类型时，自动设置重复模式
    const dietType = eventsStore.getDietType(value) as any
    if (dietType && dietType.suggested_frequency) {
      enableRecurrence.value = true
      recurrenceFrequency.value = dietType.suggested_frequency
      recurrenceInterval.value = dietType.suggested_interval || 1

      // 根据建议的每周次数设置重复次数
      if (dietType.suggested_frequency_per_week) {
        recurrenceCount.value = dietType.suggested_frequency_per_week
      } else {
        // 默认重复次数
        recurrenceCount.value = dietType.suggested_frequency === 'daily' ? 30 :
                                dietType.suggested_frequency === 'weekly' ? 12 : 6
      }

      window.$message?.info(`已根据${dietType.name}的建议自动设置重复模式：${dietType.cycle_description || ''}`)
    }
  }
}

// 处理饮食跟踪数据更新
const handleDietTrackingUpdate = (fieldName: string, value: any) => {
  if (!form.extra_data) {
    form.extra_data = {}
  }
  form.extra_data[fieldName] = value
}

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    // 构建重复模式
    if (enableRecurrence.value) {
      form.recurrence_pattern = {
        frequency: recurrenceFrequency.value,
        interval: recurrenceInterval.value,
        count: recurrenceCount.value || undefined,
        end_date: recurrenceEndDateValue.value ? formatDate(new Date(recurrenceEndDateValue.value), 'YYYY-MM-DD') : undefined
      }
    } else {
      form.recurrence_pattern = undefined
    }

    const result = await eventsStore.createEvent(form)
    if (result) {
      window.$message?.success('事件创建成功')
      router.back()
    }
  } catch (error) {
    console.error('Create event error:', error)
  } finally {
    loading.value = false
  }
}

// 处理事件类型参数
const handleEventTypeParam = () => {
  const eventTypeId = route.query.eventTypeId
  if (eventTypeId) {
    const typeId = parseInt(eventTypeId as string)
    if (!isNaN(typeId)) {
      isFromPopover.value = true // 标记为从 popover 选择
      form.event_type_id = typeId
      handleEventTypeChange(typeId)
    }
  } else {
    // 如果没有参数，重置状态
    isFromPopover.value = false
    form.event_type_id = null as any
    selectedEventType.value = null
  }
}

// 监听路由变化
watch(() => route.query.eventTypeId, () => {
  handleEventTypeParam()
})

// 初始化
onMounted(async () => {
  await eventsStore.init()

  // 设置默认开始日期为今天
  const today = new Date()
  startDateValue.value = today.getTime()
  form.start_date = formatDate(today, 'YYYY-MM-DD')

  // 处理事件类型参数
  handleEventTypeParam()
})
</script>

<style scoped>
.create-event-page {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  border-bottom: 1px solid #e0e0e0;
  background: white;
}

.page-header h1 {
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.page-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background: #f5f5f5;
}

.page-content .n-form {
  max-width: 900px;
  margin: 0 auto;
  background: white;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.dynamic-field {
  margin-top: 16px;
}

.time-range-container {
  width: 100%;
}

.time-input-group {
  display: flex;
  align-items: center;
  gap: 12px;
}

.time-separator {
  color: #666;
  font-size: 16px;
  font-weight: 500;
  flex-shrink: 0;
}

.time-display {
  margin-top: 8px;
  padding: 8px 12px;
  background: #f5f5f5;
  border-radius: 6px;
  color: #333;
  font-size: 14px;
  text-align: center;
  border: 1px solid #e0e0e0;
}

/* 事件类型显示 */
.event-type-display {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.event-type-tag {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border-radius: 20px;
  color: white;
  font-size: 14px;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  flex: 1;
}

.event-type-name {
  color: white;
}

@media (max-width: 768px) {
  .page-header {
    padding: 12px 16px;
  }

  .page-content {
    padding: 12px;
  }

  .page-content .n-form {
    padding: 12px;
  }

  .event-type-tag {
    font-size: 13px;
    padding: 6px 12px;
  }
}
</style>
